/**
 *  \file   flash_allocation.c
 *  \author Miora ANDRIAMANOHARISOA, Loic MINGHETTI
 *  \date   PFE 2011
 **/


#include "include.h"

// common variables stored in memory 
unsigned int node_id;
int sensor_offset;
unsigned int sensor_data_counter = 0;
uint8_t node_hop_count; // default is 1

// Flash memory allocation
#define FLASH_SENSOR_OFFSET INFOD_START
#define FLASH_NODE_ID (INFOD_START+2)
#define FLASH_NODE_HOP_COUNT (INFOD_START+4)
#define FLASH_SENSOR_DATA_COUNTER (INFOD_START+6)

// save flash data
void flash_save_config() {
	// need to be cleared first to prevent dommage then evrything is written again 
	flash_erase_segment((unsigned int *) INFOD_START);
    if(flash_write_word((unsigned int *) FLASH_NODE_ID, node_id) != 0) {
        printf("\r\n(!) Failed writing to segment D\r\n");
    }
    if(flash_write_word((unsigned int *) FLASH_SENSOR_OFFSET, sensor_offset) != 0) {
        printf("\r\n(!) Failed writing to segment D\r\n");
    }
    if(flash_write_word((unsigned int *) FLASH_NODE_HOP_COUNT, node_hop_count) != 0) {
        printf("\r\n(!) Failed writing to segment D\r\n");
    }
    if(flash_write_word((unsigned int *) FLASH_SENSOR_DATA_COUNTER, sensor_data_counter) != 0) {
        printf("\r\n(!) Failed writing to segment D\r\n");
    }
}


void flash_allocation_init(void) {
	sensor_offset = *((int *) FLASH_SENSOR_OFFSET);
	node_id = *((unsigned int *) FLASH_NODE_ID);
	node_hop_count = *((uint8_t *) FLASH_NODE_HOP_COUNT);
	sensor_data_counter = *((unsigned int *) FLASH_SENSOR_DATA_COUNTER);
}
